package com.itheima.commons;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;

/**
 * @author Tang
 * @date 2023/1/7
 */
@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
    @Autowired
    private HttpSession session;

    //插入数据时会调用这个方法，自动填充字段
    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("插入数据时自动填充字段");
        metaObject.setValue("createTime", LocalDateTime.now());
        metaObject.setValue("updateTime", LocalDateTime.now());
        //Long employeeId = (Long) session.getAttribute("employeeId");
        //改用ThreadLocal获取员工id
        Long employeeId = BaseContext.getCurrentId();
        metaObject.setValue("createUser", employeeId);
        metaObject.setValue("updateUser", employeeId);
//        metaObject.setValue("isDeleted", 0);
    }

    //更新数据时会调用这个方法，自动填充字段
    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("MyMetaObjectHandler 线程id: {}",Thread.currentThread().getId());
        log.info("更新数据时自动填充字段");
        metaObject.setValue("updateTime", LocalDateTime.now());
        //Long employeeId = (Long) session.getAttribute("employeeId");
        //改用ThreadLocal获取员工id
        Long employeeId = BaseContext.getCurrentId();
        metaObject.setValue("updateUser", employeeId);
    }
}
